package proto;

import com.sun.javafx.functions.Function0;
import com.sun.javafx.functions.Function1;
import javafx.lang.FX;

public class TaskExecutorImpl {
    private Function0<Void> task;
    private Function1<Void, ? super Object> taskCompletionHandler;
    private Thread thread;

    public void setTask(Function0<Void> fn){
        task = fn;
    }

    public void setTaskCompletionHandler(Function1<Void, ? super Object> fn){
        taskCompletionHandler = fn;
    }

    public void signalInterrupt(){
        if(thread!= null && thread.isAlive()){
            try {
                thread.join(50);
                System.out.println ("Stopping ");
            } catch (InterruptedException ex) {
                thread.interrupted();
            }
        }
    }

    public void run(){
        if(task == null){
            throw new RuntimeException("Unable to run empty task");
        }
        thread = new Thread(new Runnable(){
            @Override
            public void run() {
                Void d = task.invoke();
                return;
            }
        }, "FxTaskRunner-"+Thread.currentThread().getId());
        FX.deferAction(new Function0<Void>(){
            @Override public Void invoke(){
                thread.start();
                return null;
            }
        });
        
    }
}
